// pages/orderDetail/orderDetail.js
const app = getApp()
import http from "../../utils/http"
import util from "../../utils/util"

var QQMapWX = require('../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk');
// import QQMapWX from "../../../utils/qqmap-wx-jssdk"
var qqmapsdk;
const QQMapKey = 'RZ3BZ-GKDCU-425VO-45M7C-GHFVT-ZTFJ5'; //使用在腾讯位置服务申请的key


Page({

  /**
   * 页面的初始数据
   */
  data: {
    order_id: '',
    info: '',
    show: false,
    images: [],
    before_images: [],
    after_images: [],
    safeBottom: `30px`,
    settle: '',
    isCallMobile: false,
    currentLocationDistance: {},
    showLocationPopup: false,
    markers: [],
    currentLocation: {},
    showServerPopup: false,
    showServerInfoPopup: false,
    tabActive: 0, // chu_fang
    commentConfig: {},
    sign_type: "",
    content: "",
    score_type: "",



    showSignaturePage: false,
    isSignatureFinish: false,
    moveLength: 0, //移动一定距离后才能提交保存
    canvasTempWidth: wx.getSystemInfoSync().screenWidth,
    canvasTempHeight: wx.getSystemInfoSync().screenWidth * 0.5,
    signImage: "",
    showSpreadPopup: false
  },

  copy(event) {
    wx.setClipboardData({
      data: event.currentTarget.dataset.content,
      success(res) {
        util.toast('已复制')
      }
    })
  },
  navigation() {
    wx.openLocation({
      latitude: Number(this.data.info.orderAddress.lat),
      longitude: Number(this.data.info.orderAddress.lng),
      name: this.data.info.orderAddress.area,
      scale: 18
    })
  },
  call() {
    const that = this;
    wx.makePhoneCall({
      phoneNumber: this.data.info.orderAddress.mobile,
      success: function () {
        console.log("成功拨打电话")
        that.setData({
          isCallMobile: true
        })
        // this.go()
      }
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  showUpload() {
    this.setData({
      show: true
    })
  },
  delImages(e) {
    let index = e.currentTarget.dataset.index
    let name = e.currentTarget.dataset.name
    let arr = this.data[name]
    arr.splice(index, 1)
    this.setData({
      [name]: arr
    })
  },
  chooseImages(e) {
    let index = e.currentTarget.dataset.index;
    let name = e.currentTarget.dataset.name;
    let arr = this.data[name];


    wx.chooseMedia({
      count: 9 - arr.length,
      mediaType: ['image'],
      sourceType: ['camera', 'album'],
      sizeType: ['compressed'],
      camera: 'back',
      success: (res) => {
        const upload = res.tempFiles.map(tempFile => {
          return http.upload(tempFile.tempFilePath, {
            type: 'image'
          }).then(res => res.data.url)
        })
        console.log(upload)
        Promise.all(upload).then(res => {
          console.log(res)
          arr.push(...res)
          this.setData({
            [name]: arr
          })
        })
      },
      fail: (err) => {
        reject(err)
      }
    })

    return
    http.chooseImg(['camera', 'album'], true, true, wx.getStorageSync('token'), null, 9 - arr.length).then(res => {

      if (index !== undefined) {
        arr.splice(index, 1, res.data.url)
      } else {
        arr.push(res.data.url)
      }
      this.setData({
        [name]: arr
      })
    })
  },
  getInfo() {
    http.get('order/orderInfo', {
      id: this.data.order_id
    }).then(res => {
      // 处理房屋照片
      res.data.home_image_arr = res.data.home_image.split(',');
      
      this.setData({
        info: res.data,
        markers: [{
          id: "ordermarker",
          latitude: res.data.orderAddress.lat,
          longitude: res.data.orderAddress.lng,
          iconPath: '/static/index/order/navigation_2.png',
          width: "36rpx",
          height: "40rpx"
          // callout: {
          //   content: '文本内容',
          //   color: '#ff0000',
          //   fontSize: 14,
          //   borderWidth: 2,
          //   borderRadius: 10,
          //   borderColor: '#000000',
          //   bgColor: '#fff',
          //   padding: 5,
          //   display: 'ALWAYS',
          //   textAlign: 'center'
          // }
        }]
      })
      if (res.data.is_service <= 0 && res.data.status === 3) {
        this.initGetLocationFlunction()
      }

      if (res.data.is_settle > 0) {
        this.getSettle()
      }

    })
  },
  getSettle() {
    http.get('order/priceInfo', {
      id: this.data.order_id
    }).then(res => {
      this.setData({
        settle: res.data
      })
    })
  },
  accept() {
    http.get('order/skillaccept', {
      id: this.data.order_id
    }, true, false).then(res => {
      util.toast('抢单成功')
      this.getInfo()
    }).catch(e => {
      let data = e.data
      if (data.code === 2) {
        util.toast(data.msg)
      } else if (data.code === 0) {
        util.toast(data.data)
      }
    })
  },
  go() {
    const that = this;
    if (!this.data.isCallMobile) {
      wx.makePhoneCall({
        phoneNumber: this.data.info.orderAddress.mobile,
        success: function () {
          console.log("成功拨打电话")
          that.setData({
            isCallMobile: true
          })
          // this.go()
        }
      })
      return
    }

    http.get('order/skillgo', {
      id: this.data.order_id
    }).then(res => {
      this.getInfo()
    })
  },
  arrive() {
    // if (this.data.images.length === 0) return util.toast('请上传图片')
    http.get('order/skillreach', {
      id: this.data.order_id,
      reach_images: this.data.images.join(',')
    }).then(res => {
      this.setData({
        images: [],
        show: false,
        showLocationPopup: false
      })
      this.getInfo()
    })
  },
  finish() {
    if (this.data.images.length === 0) return util.toast('请上传图片')
    http.get('order/skillfinish', {
      id: this.data.order_id,
      finish_images: this.data.images.join(',')
    }).then(res => {
      this.setData({
        images: [],
        show: false
      })
      this.getInfo()
    })
  },
  start() {
    wx.showModal({
      // title: '',
      title: '确认开始服务?',
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {
          http.get('order/skillstart', {
            id: this.data.order_id
          }).then(res => {
            this.getInfo()
          })
        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const high = app.globalData.safeBottom
    this.setData({
      order_id: options.id,
      safeBottom: `${high}px`
    })

    wx.getSystemInfo({
      success: res => {
        this.setData({
          statusBarHeight: res.statusBarHeight // 获取状态栏的高度
        })
      }
    })

    // 获取胶囊信息
    this.data.capsule = wx.getMenuButtonBoundingClientRect() // 获取胶囊按钮的信息
    this.setData({
      capsuleTop: this.data.capsule.top, //  胶囊距离屏幕顶部的距离
      capsuleHeight: this.data.capsule.height, // 胶囊高度
    })
    this.setData({
      // 导航栏高度=状态栏高度+胶囊按钮的高度+（胶囊按钮距离顶部的距离-状态栏的高度）*2
      navbarHeight: (this.data.capsule.top - this.data.statusBarHeight) * 2 + this.data.capsule.height + this.data.statusBarHeight // 导航栏高度
    })

    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: QQMapKey
    });
    this.getCommentConfig()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    //第一个canvas
    this.canvasContext = wx.createCanvasContext('canvas');
    this.initCanvas()
    //第二个canvas
    this.ctx2 = wx.createCanvasContext('canvas-temp');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    this.getInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  backs() {
    wx.navigateBack()
  },

  //定位方法
  initLocationPersmiss() {
    var _this = this;
    wx.getSetting({
      success: (res) => {
        console.log(res)
        // res.authSetting['scope.userLocation'] == undefined  表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false  表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true  表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          this.clearGetAddressTimer()
          //未授权
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                //取消授权
                wx.showToast({
                  title: '拒绝授权 暂时无法使用本功能',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      _this.initGetLocationFlunction();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //用户首次进入页面,调用wx.getLocation的API
          _this.initGetLocationFlunction();
        } else {
          console.log('授权成功')
          //调用wx.getLocation的API
          _this.initGetLocationFlunction();
        }
      }
    })

  },
  initGetLocationFlunction(isRefresh) {
    let that = this;
    const {
      info
    } = this.data;
    console.log(info.orderAddress)
    // this.setData({isUpdateLocatin:true})
    // wx.getLocation({
    //   type: 'wgs84',
    //   isHighAccuracy: true,
    //   success(res) {
    //     console.log(res)
    //     let distances =  that.getDistances(res.latitude, res.longitude, Number(info.orderAddress.lat), Number(info.orderAddress.lng))
    //     console.log(distances)
    //     that.setData({
    //       currentLocationDistance: distances
    //     })
    //   },
    //   fail(err) {
    //     console.log(err)
    //   }
    // })
    // return

    qqmapsdk.reverseGeocoder({
      success: function (res) {
        let result = res.result;
        console.log(res);
        that.setData({
          currentLocation: result
        })
        that.calculateDistance(result)
      },
      fail: function (res) {
        console.log(res.status, res.message);
        wx.showToast({
          title: '获取地理位置失败：' + res.message,
          icon: "none"
        })
        that.setData({
          currentLocation: null
        })
      },
      complete: function (res) {
        console.log(res.status, res.message);
      }
    })
  },

  calculateDistance(result) {
    let self = this;
    let {
      info
    } = self.data;
    qqmapsdk.calculateDistance({
      from: {
        latitude: result.location.lat,
        longitude: result.location.lng
      }, // 从以后用户的定位算
      to: [{
        latitude: info.orderAddress.lat,
        longitude: info.orderAddress.lng
      }],
      mode: 'straight',
      success: (res) => {
        console.log(res)
        let elements = res.result.elements;
        self.setData({
          currentLocationDistance: elements[0]
        })
        if (elements[0] && elements[0].distance !== null && elements[0].distance !== undefined && elements[0].distance <= 100) {
          this.setData({
            showLocationPopup: true
          })
        }
      },
      fail: function (failRes) {
        console.log(failRes)
      },
      complete: function (completeRes) {}
    })
  },

  onCloseLocationPopup() {
    this.setData({
      showLocationPopup: false
    })
  },

  arriveAction() {
    this.setData({
      showLocationPopup: true
    })
    this.initGetLocationFlunction()
    // http.get('order/skillreach', {
    //   id: this.data.order_id,
    //   reach_images: this.data.images.join(',')
    // }).then(res => {
    //   this.setData({
    //     images: [],
    //     show: false
    //   })
    //   this.getInfo()
    // })
  },

  finishAction() {
    this.setData({
      showServerPopup: true
    })
  },

  onCloseServerPopup() {
    this.setData({
      showServerPopup: false,
      // sign_type: "",
      // score_type: "",
      // content: "",
      // signImage: "",
      before_images: [],
      after_images: [],
    })
  },
  showServerInfoPopupAction() {
    this.setData({
      showServerInfoPopup: true,
      sign_type: "",
      score_type: "",
      content: "",
      signImage: "",
    })
  },
  onCloseServerInfoPopup() {
    this.setData({
      showServerInfoPopup: false,

    })
  },

  nextAction() {
    const {
      tabActive
    } = this.data;
    console.log(tabActive, tabActive >= 4 ? 0 : tabActive + 1)
    this.setData({
      tabActive: tabActive >= 4 ? 0 : tabActive + 1
    })
  },
  contentConfirmAction() {
    const {
      sign_type,
      score_type,
      content,
      signImage
    } = this.data;
    if (!this.data.sign_type) {
      util.toast('请选择签名类型！')
      return
    } else if (!this.data.score_type) {
      util.toast('请选择满意度！')
      return
    } else if (!this.data.content) {
      util.toast('请填写评价内容！')
      return
    } else if (!this.data.signImage) {
      util.toast('请签名！')
      return
    }
    // wx.showLoading({
    //   title: '请稍后...',
    // })
    http.post('comment/commentAdd', {
      order_id: this.data.order_id,
      sign_type,
      score_type,
      content,
      sign_img: signImage
    }, true).then(res => {
      // this.setData({
      //   showServerInfoPopup: false
      // })
      this.onCloseServerInfoPopup()
      this.getInfo()
    })

  },
  onChange(event) {
    this.setData({
      tabActive: event.detail.name
    })
  },

  getCommentConfig() {
    // if (this.data.images.length === 0) return util.toast('请上传图片')
    http.get('comment/getConfig', {
      // id: this.data.order_id,
      // reach_images: this.data.images.join(',')
    }).then(res => {
      console.log(res)
      this.setData({
        commentConfig: res.data
      })
    })
  },


  //跳转签名页面
  toSign() {
    this.setData({
      showSignaturePage: true
    });
  },


  //生成电子巡检单
  makeEOrder() {
    if (this.data.sign == '') {
      wx.showToast({
        title: '请先完成商户签字',
        icon: 'none'
      })
    } else {

    }
  },
  // 签名部分
  hideSignPage() {

    this.setData({
      showSignaturePage: false
    });
    this.clearCanvas()
  },
  confirmSign() {
    let _this = this
    _this.generateSignImage('canvas').then(res => {
      console.log('图片地址：', res)

      wx.getImageInfo({
        src: res,
        success(info) {
          let width = info.width
          let height = info.height
          //先重置canvas-temp
          _this.ctx2.draw(false, () => {
            let dx = _this.data.canvasTempWidth
            let dy = _this.data.canvasTempHeight
            //把原点移动到中心点位置
            _this.ctx2.translate(dx / 2, dy / 2)
            _this.ctx2.rotate(270 * Math.PI / 180)

            let dWidth = dx / height * width
            let dHeight = dx
            //drawImage参数说明
            //imageResource
            //imageResource的左上角在目标 canvas 上 x 轴的位置
            //imageResource的左上角在目标 canvas 上 y 轴的位置
            //在目标画布上绘制 imageResource 的宽度，允许对绘制的 imageResource 进行缩放
            //在目标画布上绘制 imageResource 的高度，允许对绘制的 imageResource 进行缩放

            _this.ctx2.drawImage(res, -dWidth / 2, -dHeight / 2, dWidth, dHeight)
            //canvas-temp图片绘制完成后
            _this.ctx2.draw(false, () => {
              _this.generateSignImage('canvas-temp').then(res => {
                console.log('图片地址：', res)
                http.upload(res, {
                  type: 'image'
                }, true).then(res => {
                  console.log(res)
                  _this.setData({
                    signImage: res.data.url
                  })
                  _this.hideSignPage()
                }).catch(err => {
                  console.log(err)
                })

              })
            })
          })
        }
      })
    })
  },
  // submitSignature(){
  //   console.log(this.data.signImage)
  //   wx.showToast({
  //     icon:'none',
  //     title: '获取sign变量图片地址提交到自己的服务器',
  //   })
  // },

  initCanvas() {
    /* 设置线条颜色 */
    this.canvasContext.setStrokeStyle('#0081ff'); //2A2A2A
    /* 设置线条粗细 */
    this.canvasContext.setLineWidth(4);
    /* 设置线条的结束端点样式 */
    this.canvasContext.setLineCap('round');
  },

  /* 触摸开始 */
  handleTouchStart(e) {
    console.log(e)
    this.drawStartX = e.changedTouches[0].x;
    this.drawStartY = e.changedTouches[0].y;
    console.log('触摸开始', this.drawStartX, this.drawStartY)
    this.canvasContext.beginPath();
  },
  /* 触摸移动 */
  handleTouchMove(e) {
    /* 记录当前位置 */
    const tempX = e.changedTouches[0].x;
    const tempY = e.changedTouches[0].y;
    // console.log('触摸移动', tempX, tempY)
    this.data.moveLength += Math.abs(this.drawStartX - tempX) + Math.abs(this.drawStartY - tempY)
    /* 画线 */
    this.canvasContext.moveTo(this.drawStartX, this.drawStartY);
    this.canvasContext.lineTo(tempX, tempY);
    this.canvasContext.stroke();

    /* 旧版draw方法，新版本不需要draw */
    this.canvasContext.draw(true);

    /* 重新记录起始位置 */
    this.drawStartX = tempX;
    this.drawStartY = tempY;
  },
  /* 触摸结束 */
  handleTouchEnd(e) {
    console.log('触摸结束')
    this.canvasContext.save();
    this.setData({
      isSignatureFinish: this.data.moveLength > 100
    })
  },
  /* 触摸取消 */
  handleTouchCancel(e) {
    console.log('触摸取消')
    this.canvasContext.save();
  },
  /* 清空画布 */
  clearCanvas() {
    console.log('清空画布')
    this.canvasContext.draw()
    this.initCanvas()
    this.data.moveLength = 0
    this.setData({
      isSignatureFinish: false
    })
  },
  /* 生成签名图片 */
  generateSignImage(canvasId) {
    console.log('Canvas生成图片')
    return new Promise((resolve, reject) => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        canvasId: canvasId, // 旧版使用id
        fileType: 'png',
        quality: 1,
        success: res => {
          resolve(res.tempFilePath)
        },
        fail: err => {
          reject(err);
        }
      })
    })
  },

  signTypeChange(e) {
    console.log(e)
    const {
      value
    } = e.currentTarget.dataset;
    this.setData({
      sign_type: value
    })
  },

  scoreTypeChange(e) {
    console.log(e)
    const {
      value
    } = e.currentTarget.dataset;
    this.setData({
      score_type: value
    })
  },
  contentChange(e) {
    console.log(e)
    const {
      value
    } = e.detail;
    this.setData({
      content: value
    })
  },


  serverFinishAction() {
    const {
      after_images,
      before_images,
      order_id,
      signImage
    } = this.data;
    if (after_images.length === 0) {
      util.toast('请上传服务前得图片！')
      return
    }
    if (before_images.length === 0) {
      util.toast('请上传服务后得图片！')
      return
    }

    http.get('order/skillfinish', {
      id: order_id,
      finish_images: after_images.join(','),
      before_images: before_images.join(','),
    }).then(res => {
      this.onCloseServerPopup()
      this.getInfo()
      setTimeout(() => {
        this.showServerInfoPopupAction()
        // this.setData({
        //   showServerInfoPopupAction: true
        // })
      })
    })

  },



  // 根据经纬度计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
  getDistances(lat1, lng1, lat2, lng2) {
    console.log(lat1, lng1, lat2, lng2)
    let EARTH_RADIUS = 6378.137; // 地球半径
    let radLat1 = lat1 * Math.PI / 180.0; //lat1 * Math.PI / 180.0=>弧度计算
    let radLat2 = lat2 * Math.PI / 180.0;
    let a = radLat1 - radLat2;
    let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; // 输出为公里
    return {
      m: s * 1000,
      km: Number(s.toFixed(2))
    }
  },

  openSpreadAction() {
    this.setData({
      showSpreadPopup: true,
      price: ""
    })
  },
  onCloseSpreadPopup(){
    this.setData({
      showSpreadPopup: false
    })
  },
  setPrice(e) {
    console.log(e)
    const {
      value
    } = e.detail;
    this.setData({
      price: value
    })
  },
  setPriceAction() {
    const {
      price, order_id
    } = this.data;
    if (!price) {
      wx.showToast({
        title: '请输入差价金额！',
      })
      return
    }
    http.get('order/setPremium', {
      id: order_id,
      price
    }).then(res => {
      this.onCloseSpreadPopup()
      this.getInfo()
    })
  }


})